chrome.contextMenus.create({ "title": "ClickTrans", "contexts": ["selection"], "onclick": translate });
//chrome.extension.onRequest.addListener(onRequest);
//function onRequest(request, sender, callback) {
//    if (request.action == 'translateTxt') {
//        translateTxt(request.url, callback);
//    }
//};
function translate() {
    chrome.tabs.getSelected(null, function(tab) {
        var target_language = localStorage["clicktrans_target_language"];
        chrome.tabs.sendRequest(tab.id, { "type": "getselection" }, function handler(response) {
            var target_language = localStorage["clicktrans_target_language"];
            if (!target_language) {
                target_language = "zh-cn";
            }
            translateTxt(response.url+target_language);
        });
    });
    
}

function translateTxt(url) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(data) {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                var data = JSON.parse(xhr.responseText);
                var translatedText = data.data.translations[0].translatedText;
                chrome.tabs.getSelected(null, function(tab) {
                chrome.tabs.sendRequest(tab.id, { "type": "popupresult","txt":translatedText }, function(response) {
                    });
                });

            }
        }
    }
    xhr.open('GET', url, true);
    xhr.send();
};

